package com.weyoung.app.service.impl;


import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weyoung.app.controller.FileController;
import com.weyoung.app.dto.req.BiographyInsertEvenReqDTO;
import com.weyoung.app.dto.resp.BiographyEventsListByFamilyDTO;
import com.weyoung.app.dto.resp.BiographyUserListByCountDTO;
import com.weyoung.app.dto.resp.BiographyUserListDTO;
import com.weyoung.app.mapper.BiographyMapper;
import com.weyoung.app.mapper.UserMapper;
import com.weyoung.app.service.BiographyService;
import com.weyoung.common.consatant.exception.ClientException;
import com.weyoung.common.enums.UserErrorCodeEnum;
import com.weyoung.common.model.entity.Biography;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

@Service
@RequiredArgsConstructor
public class BiographyServiceImpl extends ServiceImpl<BiographyMapper, Biography> implements BiographyService {
    private final BiographyMapper biographyMapper;
    private final UserMapper userMapper;
    private final StringRedisTemplate stringRedisTemplate;
    private final FileController fileController;

    @Override
    public List<BiographyUserListDTO> getBiographyUserListByUserId() {
        String userID = StpUtil.getLoginId().toString();
        if (userID == null) {
            throw new ClientException(UserErrorCodeEnum.USER_TOKEN_FAIL);
        }
        List<BiographyUserListDTO> biographyListByUserId = biographyMapper.getBiographyListByUserId(Integer.parseInt(userID));
        if (biographyListByUserId == null || biographyListByUserId.isEmpty()) {
            throw new ClientException("还未添加名人堂");
        }

        return biographyListByUserId;
    }

    @Override
    public void addEvents(BiographyInsertEvenReqDTO requestParam) throws Exception {
        //获取用户ID
        String userID = StpUtil.getLoginId().toString();
        if (userID == null) {
            throw new ClientException(UserErrorCodeEnum.USER_TOKEN_FAIL);
        }
        // 从 Redis 获取 family_id
        String familyId = stringRedisTemplate.opsForValue().get(userID);
        if (familyId == null) {
            // 如果 Redis 中没有，从数据库中查询
            familyId = userMapper.getFamilyIdByUserId(Integer.parseInt(userID));
            // 将 family_id 存入 Redis
            stringRedisTemplate.opsForValue().set(userID, familyId);
        }
        //图片文件处理
        List<MultipartFile> imageList = requestParam.getImageList();
        List<String> imageUrlList = getImageUrlList(imageList);
        Biography biography = Biography.builder()
                .userId(Integer.parseInt(userID))
                .familyId(familyId)
                .eventDate(requestParam.getEventDate())
                .biographyTitle(requestParam.getBiographyTitle())
                .biographyContent(requestParam.getBiographyContent())
                .imageUrlList(imageUrlList)
                .build();
        int insert = baseMapper.insert(biography);
        if (insert < 1) {
            throw new ClientException("添加失败");
        }
    }

    @Override
    public List<BiographyUserListByCountDTO> getBiographyUserListByCount() {
        //获取用户ID
        String userID = StpUtil.getLoginId().toString();
        if (userID == null) {
            throw new ClientException(UserErrorCodeEnum.USER_TOKEN_FAIL);
        }

        // 从 Redis 获取 family_id
        String familyId = stringRedisTemplate.opsForValue().get(userID);
        if (familyId == null) {
            // 如果 Redis 中没有，从数据库中查询
            familyId = userMapper.getFamilyIdByUserId(Integer.parseInt(userID));
            // 将 family_id 存入 Redis
            stringRedisTemplate.opsForValue().set(userID, familyId);
        }
        return biographyMapper.getBiographyUserListByCount(familyId);
    }

    @Override
    public List<BiographyEventsListByFamilyDTO> getBiographyEventsListByFamily() {
         //获取用户ID
        String userID = StpUtil.getLoginId().toString();
        if (userID == null) {
            throw new ClientException(UserErrorCodeEnum.USER_TOKEN_FAIL);
        }

        // 从 Redis 获取 family_id
        String familyId = stringRedisTemplate.opsForValue().get(userID);
        if (familyId == null) {
            // 如果 Redis 中没有，从数据库中查询
            familyId = userMapper.getFamilyIdByUserId(Integer.parseInt(userID));
            // 将 family_id 存入 Redis
            stringRedisTemplate.opsForValue().set(userID, familyId);
        }
        List<BiographyEventsListByFamilyDTO> list = biographyMapper.getBiographyEventsListByFamilyId(familyId);
        if (list == null || list.isEmpty()) {
            throw new ClientException("还未添加名人堂");
        }
        return list;
    }

    /**
     * 获取文件url列表
     *
     * @param imageList 图片列表
     * @return 文件列表
     * @throws Exception 异常
     */
    public List<String> getImageUrlList(List<MultipartFile> imageList) throws Exception {
        ArrayList<String> list = new ArrayList<>();
        for (MultipartFile image : imageList) {
            String fileExtension = getFileUrl(image);
            list.add(fileExtension);
        }
        return list;
    }

    /**
     * 上传文件
     *
     * @param file 文件
     * @return 文件url
     * @throws Exception 异常
     */
    private String getFileUrl(MultipartFile file) throws Exception {
        String filename = file.getOriginalFilename();
        String fileExtension = null;
        if (filename.lastIndexOf(".") != -1 && filename.lastIndexOf(".") != 0) {
            fileExtension = filename.substring(filename.lastIndexOf(".") + 1);
        } else {
             throw new ClientException("上传失败，请重新上传");
        }
        if (fileExtension == null || fileExtension.isEmpty()) {
            throw new ClientException("上传失败，请重新上传");
        }
        // 允许的图片后缀
        String[] allowedExtensions = {"jpg", "jpeg", "png", "gif"};
        boolean isValidExtension = false;
        for (String extension : allowedExtensions) {
          if (fileExtension.equalsIgnoreCase(extension)) {
                isValidExtension = true;
                break;
          }
        }
        if (!isValidExtension) {
          throw new ClientException("上传失败，请重新上传");
        }
        return fileController.uploadImage(file);
    }


}